// #include "./ref_test.h"
// #include "./earcut.hpp"

// #include <assert.h>

// DrawCall::DrawCall() {}

// // 是否实例化
// void DrawCall::Build(vsg::ref_ptr<vsg::Group> _parent, bool _instance) {
//   instance = _instance;

//   // 将参数置为空
//   vertexes = nullptr;
//   indexes = nullptr;
//   matCol012 = nullptr;

//   // 创建所需对象，将绘制命令添加到父节点下
//   if (!instance) {
//     draw_commands = vsg::Commands::create();

//     bind_vertex = vsg::BindVertexBuffers::create();
//     bind_index = vsg::BindIndexBuffer::create();
//     draw_config = vsg::DrawIndexed::create();

//     draw_commands->addChild(bind_vertex);
//     draw_commands->addChild(bind_index);
//     draw_commands->addChild(draw_config);

//     _parent->addChild(draw_commands);
//   } else {
//     draw_commands = vsg::Commands::create();

//     bind_vertex = vsg::BindVertexBuffers::create();
//     bind_mat = vsg::BindVertexBuffers::create();
//     bind_index = vsg::BindIndexBuffer::create();
//     draw_config = vsg::DrawIndexed::create();

//     draw_commands->addChild(bind_vertex);
//     draw_commands->addChild(bind_mat);
//     draw_commands->addChild(bind_index);
//     draw_commands->addChild(draw_config);

//     _parent->addChild(draw_commands);
//   }
// }

// void DrawCall::Update() {
//   // 必须确保有数据
//   if (vertexes == nullptr || indexes == nullptr || vertexes->size() == 0 || indexes->size() == 0) {
//     assert(0);
//   }
//   if ((instance && matCol012 == nullptr) || (instance && matCol012->size() == 0)) {
//     assert(0);
//   }

//   // 实例化，多绑定逐实例的变换矩阵
//   if (!instance) {
//     auto bind_vertex_t = vsg::BindVertexBuffers::create(0, vsg::DataList{vertexes});
//     (*bind_vertex) = (*bind_vertex_t);
//     vertexes->properties.dataVariance = vsg::STATIC_DATA;
//     vertexes->dirty();

//     auto bind_index_t = vsg::BindIndexBuffer::create(indexes);
//     (*bind_index) = (*bind_index_t);
//     indexes->properties.dataVariance = vsg::STATIC_DATA;
//     indexes->dirty();

//     auto draw_config_t = vsg::DrawIndexed::create(indexes->size(), 1, 0, 0, 0);
//     (*draw_config) = (*draw_config_t);
//   } else {
//     auto bind_vertex_t = vsg::BindVertexBuffers::create(0, vsg::DataList{vertexes});
//     (*bind_vertex) = (*bind_vertex_t);
//     vertexes->properties.dataVariance = vsg::STATIC_DATA;
//     vertexes->dirty();

//     auto bind_mat_t = vsg::BindVertexBuffers::create(1, vsg::DataList{matCol012});
//     (*bind_mat) = (*bind_mat_t);
//     matCol012->properties.dataVariance = vsg::STATIC_DATA;
//     matCol012->dirty();

//     auto bind_index_t = vsg::BindIndexBuffer::create(indexes);
//     (*bind_index) = (*bind_index_t);
//     indexes->properties.dataVariance = vsg::STATIC_DATA;
//     indexes->dirty();

//     auto draw_config_t = vsg::DrawIndexed::create(indexes->size(), matCol012->size() / 3, 0, 0, 0);
//     (*draw_config) = (*draw_config_t);
//   }
// }

// vsg::ref_ptr<vsg::StateGroup> CreateNormalPipeline(std::string path, std::string vs_name, std::string fs_name,
//                                                    vsg::ref_ptr<vsg::DescriptorSetLayout>& descriptorSetLayout,
//                                                    vsg::ref_ptr<vsg::PipelineLayout>& pipelineLayout, VkPrimitiveTopology topology,
//                                                    VkBool32 primitiveRestartEnable) {
//   vsg::ref_ptr<vsg::StateGroup> stateGroup = nullptr;

//   vsg::Paths searchPaths;
//   searchPaths.push_back(path);
//   searchPaths.push_back("./");

//   vsg::ref_ptr<vsg::ShaderStage> vertexShader = vsg::ShaderStage::read(VK_SHADER_STAGE_VERTEX_BIT, "main", vsg::findFile(vs_name, searchPaths));
//   vsg::ref_ptr<vsg::ShaderStage> fragmentShader = vsg::ShaderStage::read(VK_SHADER_STAGE_FRAGMENT_BIT, "main", vsg::findFile(fs_name, searchPaths));
//   if (!vertexShader || !fragmentShader) {
//     return stateGroup;
//   }

//   // 描述符布局：只有1个常量缓冲区，只能在片段着色器中可见
//   vsg::DescriptorSetLayoutBindings descriptorBindings{{0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}};

//   descriptorSetLayout = vsg::DescriptorSetLayout::create(descriptorBindings);
//   vsg::PushConstantRanges pushConstantRanges{{VK_SHADER_STAGE_VERTEX_BIT, 0, 128}};

//   // 顶点着色器输入为vec2
//   vsg::VertexInputState::Bindings vertexBindingsDescriptions{VkVertexInputBindingDescription{0, sizeof(vsg::vec2), VK_VERTEX_INPUT_RATE_VERTEX}};
//   vsg::VertexInputState::Attributes vertexAttributeDescriptions{VkVertexInputAttributeDescription{0, 0, VK_FORMAT_R32G32_SFLOAT, 0}};

//   // 图元类型和重启是否启用
//   auto inputAssemblyState = vsg::InputAssemblyState::create();
//   inputAssemblyState->topology = topology;
//   inputAssemblyState->primitiveRestartEnable = primitiveRestartEnable;

//   // 禁用背面剔除
//   auto raster = vsg::RasterizationState::create();
//   raster->cullMode = VK_CULL_MODE_NONE;

//   // 使用默认的颜色混合和深度测试(关闭)
//   auto blend = vsg::ColorBlendState::create();
//   blend->logicOpEnable = VK_FALSE;

//   auto depethSten = vsg::DepthStencilState::create();
//   depethSten->depthTestEnable = VK_FALSE;
//   depethSten->depthWriteEnable = VK_FALSE;

//   vsg::GraphicsPipelineStates pipelineStates{vsg::VertexInputState::create(vertexBindingsDescriptions, vertexAttributeDescriptions),
//                                              inputAssemblyState,
//                                              raster,
//                                              vsg::MultisampleState::create(),
//                                              blend,
//                                              depethSten};

//   // 创建渲染管线
//   pipelineLayout = vsg::PipelineLayout::create(vsg::DescriptorSetLayouts{descriptorSetLayout}, pushConstantRanges);
//   auto graphicsPipeline = vsg::GraphicsPipeline::create(pipelineLayout, vsg::ShaderStages{vertexShader, fragmentShader}, pipelineStates);
//   auto bindGraphicsPipeline = vsg::BindGraphicsPipeline::create(graphicsPipeline);

//   // 绑定渲染管线
//   stateGroup = vsg::StateGroup::create();
//   stateGroup->add(bindGraphicsPipeline);

//   return stateGroup;
// }

// vsg::ref_ptr<vsg::StateGroup> CreateInstancePipeline(std::string path, std::string vs_name, std::string fs_name,
//                                                      vsg::ref_ptr<vsg::DescriptorSetLayout>& descriptorSetLayout,
//                                                      vsg::ref_ptr<vsg::PipelineLayout>& pipelineLayout, VkPrimitiveTopology topology,
//                                                      VkBool32 primitiveRestartEnable) {
//   vsg::ref_ptr<vsg::StateGroup> stateGroup = nullptr;

//   vsg::Paths searchPaths;
//   searchPaths.push_back(path);
//   searchPaths.push_back("./");

//   vsg::ref_ptr<vsg::ShaderStage> vertexShader = vsg::ShaderStage::read(VK_SHADER_STAGE_VERTEX_BIT, "main", vsg::findFile(vs_name, searchPaths));
//   vsg::ref_ptr<vsg::ShaderStage> fragmentShader = vsg::ShaderStage::read(VK_SHADER_STAGE_FRAGMENT_BIT, "main", vsg::findFile(fs_name, searchPaths));
//   if (!vertexShader || !fragmentShader) {
//     return stateGroup;
//   }

//   // 描述符布局：只有1个常量缓冲区，只能在片段着色器中可见
//   vsg::DescriptorSetLayoutBindings descriptorBindings{{0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}};

//   descriptorSetLayout = vsg::DescriptorSetLayout::create(descriptorBindings);
//   vsg::PushConstantRanges pushConstantRanges{{VK_SHADER_STAGE_VERTEX_BIT, 0, 128}};

//   // 顶点着色器输入为vec2和vec2，第二个为偏移，使用实例化渲染
//   vsg::VertexInputState::Bindings vertexBindingsDescriptions{
//       VkVertexInputBindingDescription{0, sizeof(vsg::vec2), VK_VERTEX_INPUT_RATE_VERTEX},
//       VkVertexInputBindingDescription{1, sizeof(vsg::vec3) * 3, VK_VERTEX_INPUT_RATE_INSTANCE}};

//   vsg::VertexInputState::Attributes vertexAttributeDescriptions{
//       VkVertexInputAttributeDescription{0, 0, VK_FORMAT_R32G32_SFLOAT, 0}, VkVertexInputAttributeDescription{1, 1, VK_FORMAT_R32G32B32_SFLOAT, 0},
//       VkVertexInputAttributeDescription{2, 1, VK_FORMAT_R32G32B32_SFLOAT, sizeof(vsg::vec3)},
//       VkVertexInputAttributeDescription{3, 1, VK_FORMAT_R32G32B32_SFLOAT, sizeof(vsg::vec3) * 2}};

//   // 图元类型和重启是否启用
//   auto inputAssemblyState = vsg::InputAssemblyState::create();
//   inputAssemblyState->topology = topology;
//   inputAssemblyState->primitiveRestartEnable = primitiveRestartEnable;

//   // 禁用背面剔除
//   auto raster = vsg::RasterizationState::create();
//   raster->cullMode = VK_CULL_MODE_NONE;

//   // 使用默认的颜色混合和深度测试（关闭）
//   auto blend = vsg::ColorBlendState::create();
//   blend->logicOpEnable = VK_FALSE;

//   auto depethSten = vsg::DepthStencilState::create();
//   depethSten->depthTestEnable = VK_FALSE;
//   depethSten->depthWriteEnable = VK_FALSE;

//   vsg::GraphicsPipelineStates pipelineStates{vsg::VertexInputState::create(vertexBindingsDescriptions, vertexAttributeDescriptions),
//                                              inputAssemblyState,
//                                              raster,
//                                              vsg::MultisampleState::create(),
//                                              blend,
//                                              depethSten};

//   // 创建渲染管线
//   pipelineLayout = vsg::PipelineLayout::create(vsg::DescriptorSetLayouts{descriptorSetLayout}, pushConstantRanges);
//   auto graphicsPipeline = vsg::GraphicsPipeline::create(pipelineLayout, vsg::ShaderStages{vertexShader, fragmentShader}, pipelineStates);
//   auto bindGraphicsPipeline = vsg::BindGraphicsPipeline::create(graphicsPipeline);

//   // 绑定渲染管线
//   stateGroup = vsg::StateGroup::create();
//   stateGroup->add(bindGraphicsPipeline);

//   return stateGroup;
// }

// RenderPipeline::RenderPipeline() {};

// void RenderPipeline::Build(vsg::ref_ptr<vsg::Group> parent, RenderPipelineType pipelineType) {
//   if (pipelineType == RenderPipelineType::NormalBorder) {
//     stateGroup = CreateNormalPipeline("C:/Users/dg/qlayout-test/data/shaders/output", "noinstance_vert.spv", "nofill_frag.spv", descriptorSet,
//                                       pipelineLayout, VkPrimitiveTopology::VK_PRIMITIVE_TOPOLOGY_LINE_STRIP, true);
//   } else if (pipelineType == RenderPipelineType::InstacneBorder) {
//     stateGroup = CreateInstancePipeline("C:/Users/dg/qlayout-test/data/shaders/output", "instance_vert.spv", "nofill_frag.spv", descriptorSet,
//                                         pipelineLayout, VkPrimitiveTopology::VK_PRIMITIVE_TOPOLOGY_LINE_STRIP, true);
//   } else if (pipelineType == RenderPipelineType::NormalFill) {
//     stateGroup = CreateNormalPipeline("C:/Users/dg/qlayout-test/data/shaders/output", "noinstance_vert.spv", "fill_frag.spv", descriptorSet,
//                                       pipelineLayout, VkPrimitiveTopology::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, false);
//   } else if (pipelineType == RenderPipelineType::InstanceFill) {
//     stateGroup = CreateInstancePipeline("C:/Users/dg/qlayout-test/data/shaders/output", "instance_vert.spv", "fill_frag.spv", descriptorSet,
//                                         pipelineLayout, VkPrimitiveTopology::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, false);
//   }

//   parent->addChild(stateGroup);
// };

// void RenderSystem::BuildPipeline() {
//   RenderPipelineType pipe_type;
//   for (size_t i = 0; i < (int)RenderPipelineType::Num; i++) {
//     pipe_type = RenderPipelineType(i);

//     auto& pipe = pipe_map[pipe_type];
//     pipe.Build(scene, pipe_type);
//   }
// }

// void RenderSystem::AddLayer(int layer_id) {
//   RenderStyleTag styleTag;
//   styleTag.layer = layer_id;

//   for (size_t i = 0; i < int(RenderStyleType::Num); i++) {
//     styleTag.styleType = RenderStyleType(i);

//     for (size_t j = 0; j < int(RenderPipelineType::Num); j++) {
//       styleTag.pipelineType = RenderPipelineType(j);

//       auto& style_ptr = style_map[styleTag];
//       auto& pipe = pipe_map[styleTag.pipelineType];

//       if (styleTag.pipelineType == RenderPipelineType::NormalBorder || styleTag.pipelineType == RenderPipelineType::InstacneBorder) {
//         style_ptr = new RenderStyle<Border_Uniform>();
//         style_ptr->Build(pipe.stateGroup, styleTag.layer, pipe.descriptorSet, pipe.pipelineLayout);
//         style_ptr->Update();
//       } else {
//         style_ptr = new RenderStyle<Fill_Uniform>();
//         style_ptr->Build(pipe.stateGroup, styleTag.layer, pipe.descriptorSet, pipe.pipelineLayout);
//         style_ptr->Update();
//       }
//     }
//   }
// }

// void RenderSystem::Build(vsg::ref_ptr<vsgQt::Viewer> _viewer, vsg::ref_ptr<vsg::Group> parent) {
//   viewer = _viewer;

//   scene = vsg::Group::create();
//   parent->addChild(scene);

//   BuildPipeline();
// }

// std::vector<DrawCall>& RenderSystem::GetDrawCalls(RenderStyleTag styleTag) {
//   auto it = drawCall_map.find(styleTag);
//   if (it == drawCall_map.end()) {
//     auto& drawCalls = drawCall_map[styleTag];

//     int init_drawCall_num = 4;
//     drawCalls.resize(init_drawCall_num);

//     bool instance = false;
//     if (styleTag.pipelineType == RenderPipelineType::InstanceFill || styleTag.pipelineType == RenderPipelineType::InstacneBorder) {
//       instance = true;
//     }

//     auto& style = style_map[styleTag];

//     for (auto& e : drawCalls) {
//       e.Build(style->styleGroup, instance);
//     }
//   }
//   return drawCall_map[styleTag];
// }

// DrawCall& RenderSystem::GetNewDrawCall(RenderStyleTag styleTag) {
//   auto& drawCalls = drawCall_map[styleTag];

//   bool instance = false;
//   if (styleTag.pipelineType == RenderPipelineType::InstanceFill || styleTag.pipelineType == RenderPipelineType::InstacneBorder) {
//     instance = true;
//   }

//   if (layer_has[styleTag.layer] == false) {
//     AddLayer(styleTag.layer);
//     layer_has[styleTag.layer] = true;
//   }

//   auto& style = style_map[styleTag];

//   auto& e = drawCalls.emplace_back();
//   e.Build(style->styleGroup, instance);
//   return e;
// }

// RenderSystem* RenderSystem::Instance() {
//   static RenderSystem* res = nullptr;
//   if (res == nullptr) {
//     res = new RenderSystem;
//   }
//   return res;
// }

// #include "qlib/layout/library.h"

// using namespace qlib;

// Cell::s_ptr find_top_cell(Library::s_ptr library) {
//   std::unordered_map<Cell::s_ptr, bool> cell_top;

//   for (size_t i = 0; i < library->cells.size(); i++) {
//     cell_top[library->cells[i]] = true;
//   }

//   for (size_t i = 0; i < library->cells.size(); i++) {
//     auto it = library->cells[i]->reference_map.begin();
//     while (it != library->cells[i]->reference_map.end()) {
//       cell_top[it->first] = false;
//       it++;
//     }
//   }

//   Cell::s_ptr res = nullptr;

//   auto it = cell_top.begin();
//   while (it != cell_top.end()) {
//     if (it->second == true) {
//       res = it->first;
//       break;
//     }
//     it++;
//   }

//   return res;
// }

// vsg::mat3 getTransform(qlib::Vec2d origin, double rotation, double magnification, bool x_reflection) {
//   float tx = origin.x;
//   float ty = origin.y;
//   float c = std::cos(rotation);
//   float s = std::sin(rotation);
//   float sx = magnification;
//   float sy = x_reflection ? -1 * magnification : magnification;

//   vsg::mat3 res{
//       c * sx, s * -sy, tx,  //
//       s * sx, c * sy,  ty,  //
//       0,      0,       1,   //
//   };
//   // vsg::mat3 res{
//   //     c * sx,  s * sy, 0,  //
//   //     -s * sy, c * sy, 0,  //
//   //     tx,      ty,     1,  //
//   // };

//   return res;
// }

// void find_cell_use(qlib::Cell::s_ptr cell, vsg::mat3 parent_transform, std::unordered_map<Cell::s_ptr, std::vector<vsg::mat3>>& cell_use) {
//   vsg::mat3 child_transform;
//   vsg::mat3 transform_t;

//   auto it = cell->reference_map.begin();
//   while (it != cell->reference_map.end()) {
//     for (auto& e : it->second) {
//       child_transform = getTransform(e->origin, e->rotation, e->magnification, e->x_reflection);
//       child_transform = child_transform * parent_transform;

//       auto& matrix_arr = cell_use[it->first];
//       if (e->repetition.type != RepetitionType::None) {
//         qlib::Vec2dArray offsets;
//         e->repetition.get_offsets(offsets);
//         for (auto& offset : offsets) {
//           transform_t = child_transform;
//           transform_t[2][0] += offset.x;
//           transform_t[2][1] += offset.y;

//           matrix_arr.emplace_back(transform_t);
//         }
//       } else {
//         matrix_arr.emplace_back(child_transform);
//       }
//       find_cell_use(e->cell, child_transform, cell_use);
//     }
//     it++;
//   }
// }

// struct RenderObj {
//   uint32_t layer;
//   Vec2dArray* points;

//   bool instance;
//   Vec2dArray offsets;

//   std::vector<vsg::mat3> transforms;

//   vsg::ref_ptr<vsg::vec2Array> vertexes;
//   vsg::ref_ptr<vsg::vec3Array> matCol012s;
// };

// void find_cell_render_obj(Cell::s_ptr cell, std::unordered_map<Cell::s_ptr, std::vector<RenderObj>>& cell_render_obj) {
//   auto it = cell->polygon_map.begin();

//   while (it != cell->polygon_map.end()) {
//     auto& polygon_arr = it->second;

//     for (auto& polygon : polygon_arr) {
//       auto& render_obj = cell_render_obj[cell].emplace_back();
//       render_obj.layer = polygon->layer;

//       render_obj.points = &polygon->points;
//       if (polygon->repetition.type == RepetitionType::None) {
//         render_obj.instance = false;
//       } else {
//         render_obj.instance = true;
//         polygon->repetition.get_offsets(render_obj.offsets);
//       }
//     }

//     it++;
//   }
// }

// void find_library_render_obj(qlib::Library::s_ptr library, std::unordered_map<Cell::s_ptr, std::vector<RenderObj>>& library_render_obj) {
//   for (size_t i = 0; i < library->cells.size(); i++) {
//     find_cell_render_obj(library->cells[i], library_render_obj);
//   }
// }

// void render_obj_app_reference(const std::unordered_map<Cell::s_ptr, std::vector<vsg::mat3>>& cell_use,
//                               std::unordered_map<Cell::s_ptr, std::vector<RenderObj>>& render_obj) {
//   auto it = cell_use.begin();

//   while (it != cell_use.end()) {
//     auto& render_obj_arr = render_obj[it->first];
//     auto& mat3_arr = it->second;

//     bool cell_only = true;
//     if (mat3_arr.size() > 1)
//       cell_only = false;

//     for (auto& render_obj : render_obj_arr) {
//       if (!cell_only) {
//         if (render_obj.instance != true) {
//           render_obj.instance = true;
//           render_obj.offsets.emplace_back(0, 0);
//         }

//         render_obj.transforms.reserve(render_obj.offsets.size() * mat3_arr.size());
//         for (auto& offset : render_obj.offsets) {
//           for (auto& mat3 : mat3_arr) {
//             render_obj.transforms.emplace_back(mat3);
//             render_obj.transforms.back()[2][0] += offset.x;
//             render_obj.transforms.back()[2][1] += offset.y;
//           }
//         }
//       } else {
//         render_obj.transforms.emplace_back(mat3_arr[0]);
//       }
//     }

//     it++;
//   }
// }

// void BuildBorderInstance(RenderSystem* sys, std::unordered_map<Cell::s_ptr, std::vector<RenderObj>>& render_obj_map) {
//   RenderStyleTag tag;
//   tag.pipelineType = RenderPipelineType::InstacneBorder;
//   tag.styleType = RenderStyleType::Normal;

//   auto it = render_obj_map.begin();
//   while (it != render_obj_map.end()) {
//     auto& render_obj_arr = it->second;

//     for (auto& render_obj : render_obj_arr) {
//       if (!render_obj.instance)
//         continue;

//       tag.layer = render_obj.layer;
//       auto& drawCall = sys->GetNewDrawCall(tag);

//       auto& vertexs = render_obj.vertexes;
//       vertexs = vsg::vec2Array::create(render_obj.points->size());
//       drawCall.vertexes = vertexs;

//       for (int i = 0; i < vertexs->size(); i++) {
//         (*vertexs)[i].x = (*render_obj.points)[i].x;
//         (*vertexs)[i].y = (*render_obj.points)[i].y;
//       }

//       auto& indexes = drawCall.indexes;
//       indexes = vsg::uintArray::create(render_obj.points->size() + 2);
//       for (size_t i = 0; i < indexes->size() - 1; i++) {
//         (*indexes)[i] = i;
//       }
//       (*indexes)[render_obj.points->size()] = 0;
//       (*indexes)[render_obj.points->size() + 1] = UINT32_MAX;

//       auto& matCol012 = render_obj.matCol012s;
//       matCol012 = vsg::vec3Array::create(render_obj.transforms.size() * 3);
//       drawCall.matCol012 = matCol012;
//       for (size_t i = 0; i < render_obj.transforms.size(); i++) {
//         (*matCol012)[i * 3] = render_obj.transforms[i][0];
//         (*matCol012)[i * 3 + 1] = render_obj.transforms[i][1];
//         (*matCol012)[i * 3 + 2] = render_obj.transforms[i][2];
//       }

//       drawCall.Update();
//     }

//     it++;
//   }
// }

// std::vector<uint32_t> tri_earcut(const Vec2dArray& points) {
//   // Create array
//   std::vector<std::vector<std::array<double, 2>>> polygon;
//   // Create polyline
//   std::vector<std::array<double, 2>> polyline;
//   for (auto& p : points) {
//     polyline.push_back({p.x, p.y});
//   }
//   polygon.push_back(polyline);

//   auto indices = mapbox::earcut<uint32_t>(polygon);
//   return indices;
// }

// void BuildFillInstance(RenderSystem* sys, std::unordered_map<Cell::s_ptr, std::vector<RenderObj>>& render_obj_map) {
//   RenderStyleTag tag;
//   tag.pipelineType = RenderPipelineType::InstanceFill;
//   tag.styleType = RenderStyleType::Normal;

//   auto it = render_obj_map.begin();
//   while (it != render_obj_map.end()) {
//     auto& render_obj_arr = it->second;

//     for (auto& render_obj : render_obj_arr) {
//       if (!render_obj.instance)
//         continue;

//       tag.layer = render_obj.layer;

//       auto& vertexs = render_obj.vertexes;
//       auto indexes_t = tri_earcut(*render_obj.points);

//       if (indexes_t.size() != 0) {
//         auto& drawCall = sys->GetNewDrawCall(tag);

//         drawCall.vertexes = vertexs;

//         auto& indexes = drawCall.indexes;
//         indexes = vsg::uintArray::create(indexes_t.size());
//         for (size_t i = 0; i < indexes->size(); i++) {
//           (*indexes)[i] = indexes_t[i];
//         }

//         auto& matCol012 = render_obj.matCol012s;
//         drawCall.matCol012 = matCol012;

//         drawCall.Update();
//       }
//     }

//     it++;
//   }
// }

// void BuildBorderNoInstance(RenderSystem* sys, std::unordered_map<Cell::s_ptr, std::vector<RenderObj>>& render_obj_map) {
//   std::unordered_map<uint32_t, std::pair<uint32_t, uint32_t>> drawCall_size;
//   std::unordered_map<uint32_t, std::vector<RenderObj*>> render_obj_layer_map;

//   auto it = render_obj_map.begin();
//   while (it != render_obj_map.end()) {
//     auto& render_obj_arr = it->second;

//     for (auto& render_obj : render_obj_arr) {
//       if (render_obj.instance)
//         continue;

//       auto& obj_arr = render_obj_layer_map[render_obj.layer];
//       obj_arr.emplace_back(&render_obj);

//       drawCall_size[render_obj.layer].first += render_obj.points->size();
//       drawCall_size[render_obj.layer].second += render_obj.points->size() + 2;
//     }

//     it++;
//   }

//   std::unordered_map<uint32_t, DrawCall*> drawCall_map;

//   RenderStyleTag tag;
//   tag.pipelineType = RenderPipelineType::NormalBorder;
//   tag.styleType = RenderStyleType::Normal;

//   auto it_t = drawCall_size.begin();
//   while (it_t != drawCall_size.end()) {
//     tag.layer = it_t->first;

//     auto& drawCall = sys->GetNewDrawCall(tag);
//     drawCall_map[it_t->first] = &drawCall;

//     drawCall.vertexes = vsg::vec2Array::create(it_t->second.first);
//     drawCall.indexes = vsg::uintArray::create(it_t->second.second);

//     uint32_t vertex_start = 0;
//     uint32_t index_start = 0;
//     auto& render_obj_arr = render_obj_layer_map[it_t->first];

//     for (auto& render_obj : render_obj_arr) {
//       uint32_t old_vertex_start = vertex_start;
//       for (auto& point : *render_obj->points) {
//         (*drawCall.vertexes)[vertex_start].x = point.x;
//         (*drawCall.vertexes)[vertex_start].y = point.y;

//         (*drawCall.indexes)[index_start++] = vertex_start;

//         vertex_start++;
//       }
//       (*drawCall.indexes)[index_start++] = old_vertex_start;
//       (*drawCall.indexes)[index_start++] = UINT32_MAX;
//     }

//     drawCall.Update();
//     it_t++;
//   }
// }

// void BuildFillNoInstance(RenderSystem* sys, std::unordered_map<Cell::s_ptr, std::vector<RenderObj>>& render_obj) {
//   // std::unordered_map<uint32_t, std::pair<uint32_t, uint32_t>> drawCall_size;
//   // std::unordered_map<uint32_t, std::vector<RenderObj*>> render_obj_layer_map;

//   // auto it = render_obj.begin();
//   // while (it != render_obj.end()) {
//   //   auto& render_obj_arr = it->second;

//   //   for (auto& render_obj : render_obj_arr) {
//   //     if (render_obj.instance)
//   //       continue;

//   //     auto& obj_arr = render_obj_layer_map[render_obj.layer];
//   //     obj_arr.emplace_back(&render_obj);

//   //     drawCall_size[render_obj.layer].first += render_obj.points->size();
//   //     drawCall_size[render_obj.layer].second += render_obj.points->size() + 2;
//   //   }

//   //   it++;
//   // }

//   // std::unordered_map<uint32_t, DrawCall*> drawCall_map;

//   // RenderStyleTag tag;
//   // tag.pipelineType = RenderPipelineType::NormalFill;
//   // tag.styleType = RenderStyleType::Normal;

//   // auto it_t = drawCall_size.begin();
//   // while (it_t != drawCall_size.end()) {
//   //   tag.layer = it_t->first;

//   //   auto& drawCall = sys->GetNewDrawCall(tag);
//   //   drawCall_map[it_t->first] = &drawCall;

//   //   drawCall.vertexes = vsg::vec2Array::create(it_t->second.first);
//   //   drawCall.indexes = vsg::uintArray::create(it_t->second.second);

//   //   uint32_t vertex_start = 0;
//   //   uint32_t index_start = 0;
//   //   auto& render_obj_arr = render_obj_layer_map[it_t->first];

//   //   for (auto& render_obj : render_obj_arr) {
//   //     uint32_t old_vertex_start = vertex_start;
//   //     for (auto& point : *render_obj->points) {
//   //       (*drawCall.vertexes)[vertex_start].x = point.x;
//   //       (*drawCall.vertexes)[vertex_start].y = point.y;

//   //       (*drawCall.indexes)[index_start++] = vertex_start;

//   //       vertex_start++;
//   //     }
//   //     (*drawCall.indexes)[index_start++] = old_vertex_start;
//   //     (*drawCall.indexes)[index_start++] = UINT32_MAX;
//   //   }

//   //   drawCall.Update();
//   //   it_t++;
//   // }
// }

// void path_to_polygon(qlib::Library::s_ptr library) {
//   for (size_t i = 0; i < library->cells.size(); i++) {
//     auto it = library->cells[i]->path_map.begin();
//     while (it != library->cells[i]->path_map.end()) {
//       auto& path_arr = it->second;
//       for (auto& path : path_arr) {
//         // path->to_polygons(false, 0, 0, library->cells[i]->polygon_map[qlib::Tag(path->layer,path->datatype)]);
//       }
//       it++;
//     }
//   }
// }

// bool compareDescending(RenderObj* a, RenderObj* b) {
//   return (a->transforms.size() > b->transforms.size());
// }

// #include <algorithm>

// void RenderSystem::BuildScene(qlib::Library::s_ptr library) {
//   Cell::s_ptr top_cell = find_top_cell(library);

//   std::unordered_map<Cell::s_ptr, std::vector<vsg::mat3>> cell_use;
//   vsg::mat3 transform = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};

//   find_cell_use(top_cell, transform, cell_use);

//   path_to_polygon(library);

//   std::unordered_map<Cell::s_ptr, std::vector<RenderObj>> render_obj;
//   find_library_render_obj(library, render_obj);

//   render_obj_app_reference(cell_use, render_obj);

//   std::vector<RenderObj*> render_obj_ptr;
//   auto it = render_obj.begin();
//   while (it != render_obj.end()) {
//     auto& render_obj_arr = it->second;
//     for (auto& render_obj_t : render_obj_arr) {
//       render_obj_ptr.push_back(&render_obj_t);
//     }

//     it++;
//   }

//   std::sort(render_obj_ptr.begin(), render_obj_ptr.end(), compareDescending);

//   BuildBorderInstance(this, render_obj);
//   BuildFillInstance(this, render_obj);

//   BuildBorderNoInstance(this, render_obj);
//   BuildFillNoInstance(this, render_obj);

//   viewer->compile();
// }